package com.domain.cumanager;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import org.apache.log4j.Logger;

import com.domain.Task;
import com.domain.exceptions.FailedToDispatchTask;

public class CUStub extends Thread {
	private static int s_idCount = 0;
	private String m_id;
	private Socket m_cuSocket;
	private boolean m_shouldRun;
	private PrintWriter m_out = null;
	private BufferedReader m_in = null;
	private int m_msgCountTest = 0;
	private static Logger s_logger;
	private static int m_status = 0;
	
	//TODO handle all possible exceptions
	public CUStub(Socket clientSocket) throws IOException {
		super("CUStub");
		s_logger = Logger.getLogger(CUStub.class);		
		m_cuSocket = clientSocket;
		m_out = new PrintWriter(m_cuSocket.getOutputStream(), true);
		m_in = new BufferedReader(new InputStreamReader(m_cuSocket.getInputStream()));				
		s_idCount++;
		setUpId();
		s_logger.info("CUStub created ok. id <" + m_id + ">");
		m_shouldRun = true;
	}

	private void setUpId() {
		m_id = String.valueOf(s_idCount) + "_";
		m_id = m_id + m_cuSocket.getInetAddress().getHostAddress();
		m_id = m_id + ":" + m_cuSocket.getPort();		
	}

	public String getCUId() {
		return m_id;
	}

	public void run(){
		receiveCUParameters();
		while(m_shouldRun){
			stubSleep();
			sendMessageTest();
			stubSleep();
			receiveMessageTest();
		}
	}

	private void receiveMessageTest() {
		try {
			String receivedMsg = m_in.readLine();
			s_logger.info("Received message from CU. <" + receivedMsg + ">");
		} catch (IOException e) {			
			s_logger.fatal("Failed to receive message");
			closeStub();
		}		
	}

	private void closeStub() {
		m_shouldRun = false;
		m_out.close();
		try {
			m_in.close();
			m_cuSocket.close();			
		} catch (IOException e) {
			s_logger.fatal("Failed to close resources");
		}
		s_logger.info("id :" + m_id + " closed ok");		
	}

	private void sendMessageTest() {
		m_out.println("message from stub. msg id :" + (m_msgCountTest++));
	}

	private void stubSleep() {
		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			s_logger.fatal("Interrupted while sleeping");
		}
	}

	private void receiveCUParameters() {
		try {
			String params = m_in.readLine();
			s_logger.info("Received parameters <" + params + ">");
		} catch (IOException e) {
			s_logger.fatal("Failed to receive CUs parameters");
		}
	}

	public void addTask(Task task) throws FailedToDispatchTask{
		// TODO Auto-generated method stub
		
	}
	public int getStatus() {
		return m_status;
		
	}
}
